import Md5 from 'crypto-js/md5';
import _ from 'lodash';
import request from '@/utils/request';
import { queryDataPower } from '@/services/power';

const fineBase = 'https://finereport.gw-greenenergy.com/webroot/decision/view/report';
const joinPrams = (url, params) => {
  return `${url}?${Object.entries(params)
    .map((x) => `${x[0]}=${x[1]}`)
    .join('&')}`;
};

export async function getSignature(params) {
  // 获取签名
  return request(`/signature/fineReport/sign?iframePath=${params}`);
}

export async function getFineReportIframe(params) {
  // 获取报表参数
  return request('/generation-common/finereport/getFineReportIframe', {
    method: 'POST',
    data: params,
  });
}

// 拼接好地址，return 集合
export const fetchUrls = async (menuCode) => {
  const [powerRes, viewletRes] = await Promise.all([
    queryDataPower(menuCode),
    getFineReportIframe({ menuCode: [menuCode] }),
  ]);
  const _tree = powerRes?.powers?.find((x) => x.type === 't_station')?.json || [];
  const _ids = _.flattenDeep(_tree.map((x) => x.stationId));
  const station_shadow = _ids.join(','); // 场站id逗号拼
  const TRfanruan = Md5('TianRunXinNeng2021' + station_shadow).toString();
  const viewletList = viewletRes?.dataFineReportBodyList || []; // 帆软
  const res = await Promise.all(viewletList.map((x) => getSignature(x.iframeName)));
  const result = viewletList.map((x, i) =>
    joinPrams(fineBase, {
      viewlet: x.iframeName,
      fine_digital_signature: res[i]?.result || '',
      station_shadow,
      TRfanruan,
      op: 'write',
    }),
  );
  return Promise.resolve(result);
};
